package com.cathu.lib_commonkt.base

import androidx.annotation.CallSuper
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import com.thunbu.lib_common.base.BaseFragment
import java.lang.reflect.ParameterizedType

abstract class BaseMVVMFragment<VDB : ViewDataBinding, VM : ViewModel> : BaseFragment<VDB>(){

    lateinit var vm: VM

    @CallSuper
    override fun onCreated() {
        //初始化ViewModel
        val vmClassName = (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[1].toString().split(" ")[1]
        vm = ViewModelProvider(getVMStore(),getVMFactory()).get(Class.forName(vmClassName) as Class<VM>)

        autoBindViewModel()
        onMVVMCreated()
    }


    open fun getVMFactory(): ViewModelProvider.Factory = defaultViewModelProviderFactory

    /**
     * 自动绑定 ViewModel
     */
    private fun autoBindViewModel() {
        val setVmMethod = bindViews::class.java.methods.find { method ->
            method.parameterTypes.find {clz->
                ViewModel::class.java.isAssignableFrom(clz)
            }!=null
        }
        setVmMethod?.invoke(bindViews,vm)
    }

    /**
     * 创建bindView和ViewModel后，在OnCreate方法中继续做的事情
     */
    abstract fun onMVVMCreated()


    /**
     *  <默认和 Activity 共用一个>
     */
    open fun getVMStore(): ViewModelStore = requireActivity().viewModelStore
}